package cn.cubix.flow.redisson;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class RedissonConfig {

    @Bean
    @ConditionalOnBean(RedissonProps.class)
    public RedissonClient redissonClient(RedissonProps redissonProps){
        Config config = new Config();
        if(redissonProps.getSingleServerConfig()!=null){
            BeanUtils.copyProperties(redissonProps.getSingleServerConfig(),config.useSingleServer());
        }else if(redissonProps.getMasterSlaveServersConfig()!=null){
            BeanUtils.copyProperties(redissonProps.getMasterSlaveServersConfig(),config.useMasterSlaveServers());
        }else if(redissonProps.getSentinelServersConfig()!=null){
            BeanUtils.copyProperties(redissonProps.getSentinelServersConfig(),config.useSentinelServers());
        }else if(redissonProps.getClusterServersConfig()!=null){
            BeanUtils.copyProperties(redissonProps.getClusterServersConfig(),config.useClusterServers());
        }else if(redissonProps.getReplicatedServersConfig()!=null){
            BeanUtils.copyProperties(redissonProps.getReplicatedServersConfig(),config.useReplicatedServers());
        }
        BeanUtils.copyProperties(redissonProps,config);
        return Redisson.create(config);
    }

    @Bean
    public RedissonAutoConfigurationCustomizer redissonAutoConfigurationCustomizer() {
        return configuration -> {
            if (StringUtils.isEmpty(configuration.useSingleServer().getPassword())) {
                configuration.useSingleServer().setPassword(null);
            }
        };
    }
}
